<?php

namespace App\Transformers\Page;

use App\Models\Page;
use League\Fractal\TransformerAbstract;

class PageTransformer extends TransformerAbstract
{
    public function transform(Page $page)
    {
        $category_id = $page->category_id ? $this->formatCategory($page->category) : null;
        $category = $category_id ? array_filter(array_flatten($category_id)) : [0];
        sort($category);

        return [
            'id' => $page->id,
            'category_id' =>$category,
            'title' => $page->title,
            'tags' => $page->tags,
            'content' => $page->content,
        ];
    }

    /**
     * @author Vance
     *
     * @param $res
     * @return array|null
     */
    protected function formatCategory($res)
    {
        if (count($res) == 0) {
            return null;
        }

        $data = [
            'id' => $res->id,
            'parent' => $res->parent ? $this->formatCategory($res->parent) : null,
        ];

        return $data;
    }

}